﻿using Microsoft.EntityFrameworkCore;
using ProductManagement.Domain.Entities;
using ProductManagement.Domain.Interfaces;
using ProductManagement.Infrastructure.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ProductManagement.Infrastructure.Repositories
{
    public class UserRepository : IUserRepository
    {
        private ProductDbContext _dbContext;

        public UserRepository(ProductDbContext dbContext)
        {
            _dbContext = dbContext;
        }
        public async Task AddUserAsync(User user)
        {
            await _dbContext.Users.AddAsync(user);
            await _dbContext.SaveChangesAsync();
        }

        public async Task DeleteUserAsync(int id)
        {
            var user = _dbContext.Users.Find(id);
            if (user != null)
            {
                _dbContext.Users.Remove(user);
                await _dbContext.SaveChangesAsync();
            }
        }

        public async Task<IEnumerable<User>> GetAllUsersAsync()
        {
            return await _dbContext.Users.ToListAsync();
        }

        public async Task<User> GetUserByIdAsync(int id)
        {
           return await _dbContext.Users.FindAsync(id);
        }

        public Task UpdateUserAsync(User user)
        {
            var entry = _dbContext.Entry(user);
            entry.State = EntityState.Modified;
            entry.Property(x => x.CreatedDate).IsModified = false;
            user.UpdatedDate = DateTime.UtcNow;
            return _dbContext.SaveChangesAsync();
        }
    }
}
